package com.rtsapp.version.builder.utils;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.File;
import java.io.IOException;


public class FtpPutUtil implements IPutFile {

    private final FtpConfig ftpConfig = new FtpConfig();

    private Element ftp;

    private Element getRoot() {
        if (ftp == null) {
            try {
                SAXReader saxReader = new SAXReader();
                Document dom = saxReader.read(new File("cfg/cdn.xml"));
                ftp = dom.getRootElement().element("ftp");

                ftpConfig.setServer(ftp.element("server").attributeValue("value"));
                ftpConfig.setPort(Integer.parseInt(ftp.element("port").attributeValue("value")));
                ftpConfig.setUsername(ftp.element("user").attributeValue("value"));
                ftpConfig.setPassword(ftp.element("password").attributeValue("value"));
                ftpConfig.setLocation(ftp.element("path").attributeValue("value"));

            } catch (DocumentException e) {
                e.printStackTrace();
            }
        }
        return ftp;
    }

    private FtpUtil getNewConnection() throws IOException {

        getRoot();

        FtpUtil ftpUtil = new FtpUtil();
        ftpUtil.connectServer(ftpConfig);

        return ftpUtil;
    }

    public boolean putFiles(String keyPrefix, String pathPrefix, String path) {

        FtpUtil connection = null;
        try {
            connection = getNewConnection();

            String remotePathAndName = keyPrefix + path;

            String[] remotePathAndNames = remotePathAndName.split("/");

            String remotePath = "/";

            for (int i = 0; i < remotePathAndNames.length - 1; i++) {
                String tmpRemotePath = remotePathAndNames[i] + "/";

                remotePath += tmpRemotePath;

                if (!connection.existDirectory(remotePath)) {
                    connection.createDirectory(remotePath);
                }


            }

            String remoteName = remotePathAndNames[remotePathAndNames.length - 1];


            if (connection.existFile(remoteName))//判断是否已上传
            {
                return false;
            }

            if (!connection.uploadFile(pathPrefix + path, remotePathAndName)) {
                throw new RuntimeException();
            }
        } catch (IOException e) {
            throw new RuntimeException();
        } finally {
            if (connection != null) {
                try {
                    connection.closeServer();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return true;

    }
}
